package gsw.tool.common;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * 格式化标题
 * 一般从网上下载的txt文件,标题都不规范,无法在小说app中正常显示,所以需要格式化.
 */
public class ToolTitle {
    static String[] units = {"", "十", "百", "千", "万", "十万", "百万", "千万", "亿", "十亿", "百亿", "千亿", "万亿"};
    static char[] numArray = {'零', '一', '二', '三', '四', '五', '六', '七', '八', '九'};
    static String[] mt = {"零", "一", "二", "三", "四", "五", "六", "七", "八", "九", "", "十", "百"};

    public static void main(String[] args) {
        formatTitle("D:\\2.txt", "D:\\永夜君王.txt");
    }

    /**
     * 格式化文章标题
     *
     * @param oldPath
     * @param newPath
     */
    public static void formatTitle(String oldPath, String newPath) {
        FileWriter fw = null;
        BufferedReader br = null;
        try {
            fw = new FileWriter(newPath, true);
            br = new BufferedReader(new InputStreamReader(new FileInputStream(oldPath), "UTF-8"));
            String line = null;
            int ll = 1;
            while ((line = br.readLine()) != null) {
                if (line.startsWith("章")) {
                    for (String s : mt) {
                        if (line.contains(s)) {
                            line = line.replace(s, "");
                        }
                    }
                    line = line.replace("章", "第" + formatInt(ll) + "章  ");
                    System.out.println(line + "\r\n");
                    ll++;
                }
                fw.write(line + "\r\n");
                fw.flush();
            }
            br.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fw != null) {
                try {
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 阿拉伯数字转中文汉字
     *
     * @param num
     * @return
     */
    private static String formatInt(int num) {
        char[] val = String.valueOf(num).toCharArray();
        int len = val.length;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < len; i++) {
            String m = val[i] + "";
            int n = Integer.valueOf(m);
            boolean isZero = n == 0;
            String unit = units[(len - 1) - i];
            if (isZero) {
                if ('0' == val[i - 1]) {
                    // not need process if the last digital bits is 0
                    continue;
                } else {
                    // no unit for 0
                    sb.append(numArray[n]);
                }
            } else {
                sb.append(numArray[n]);
                sb.append(unit);
            }
        }
        return sb.toString();
    }
}
